/*
 * Copyright (c) 2011, 2012 Alexander Kluth <alexander.kluth@outlook.com>
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package hardyhttp.server;

import hardyhttp.filesystem.Logger;
import java.io.*;
import java.net.*;
import com.sun.net.httpserver.*;

import hardyhttp.server.handler.*;
import hardyhttp.config.*;

/**
 * Main class for the http-server itself
 * 
 * @author akluth
 */
public class Httpd implements Runnable
{
    InetSocketAddress address;
    HttpServer httpd;
    Logger logger;
    CommonHandler commonHandler;
    ServerConfig config;
    
    
    /**
     * C'tor, simply assigns a port
     * 
     * @param port 
     */
    public Httpd(ServerConfig config, Logger logger)
    {
        this.logger = logger;
        this.config = config;
        
        address = new InetSocketAddress(config.port);
    }
    
    
    /**
     * Method called when Hardyhttp.java is calling th.start();
     */
    @Override
    public void run()
    {
        startHttpd();
    }
    
    
    /**
     * Creates a new context and starts the server.
     * 
     * @return false if start failed, true otherwise
     */
    public boolean startHttpd()
    {
        try
        {
            logger.logEvent("[HTTPD]  Initializing httpd...");
            httpd = HttpServer.create(address, 0);
            
            logger.logEvent("[HTTPD]  Creating handler...");
            commonHandler = new CommonHandler(logger, config.htdocs, config.php);
            httpd.createContext("/", commonHandler.commonHandler);
            
            logger.logEvent("[HTTPD]  Binding server to port... " + address.getPort());
            httpd.start();
            
            logger.logEvent("[HTTPD]  httpd started, listening on port " + address.getPort());
        }
        
        catch (IOException ioe)
        {
            logger.logEvent("[HTTPD]  CRITICAL: Starting failed, error in Httpd.java: " + ioe.getMessage());
            return false;
        }
    
        return true;
    }
}
